package com.isunimp.sample.java.nio;

import java.io.*;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: Socker
 * @Description: TODO
 * @Author: isunimp
 * @Date: 2018/8/10
 */
public class Socket {


    static public void main(String[] args) throws Exception {

        try {
            String address = "120.132.81.2";
            address = "127.0.0.1";
            java.net.Socket s = new java.net.Socket(address, 3009);

            //构建IO
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();

            final BufferedReader br = new BufferedReader(new InputStreamReader(is));
            final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

            //向服务器端发送一条消息
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMddHHmmss");
            final String s1 = simpleDateFormat.format(date);

            bw.write("AP CH-WLY1,05NHXt3JShVQ,882CF25B,A2,7FFF,7FFF,7F,18,1068,1067,0F67,01,01," + s1);
            bw.flush();
            String mess = br.readLine();
            System.out.println("服务器：" + mess);
//            Thread.sleep(50000000);
//            new Thread(new Runnable() {
//                public void run() {
//                    while (true) {
//                        //读取服务器返回的消息
//                        try {
//                            String mess = br.readLine();
//                            System.out.println("服务器：" + mess);
//                            Thread.sleep(2000);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }).start();

            new Thread(new Runnable() {
                public void run() {
                    for (int idx = 0; idx < 50; ++idx) {
                        try {
                            bw.write("AP CH-WLY1,05NHXt3JShVQ,882CF25B,A2,7FFF,7FFF,7F,18,1068,1067,0F67,01,01," + s1);
                            bw.flush();
                            Thread.sleep(1000);
                            String mess = br.readLine();
                            System.out.println("服务器：" + mess);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();



            Thread.sleep(999999999);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
